package spider

import (
	"log"
	"net/http"

	"github.com/PuerkitoBio/goquery"
)

type Menu struct {
	Addr string
	Name string
}

type MenuGraber struct {
}

func NewMenuGraber() *MenuGraber {
	return &MenuGraber{}
}

func (g *MenuGraber) GrabMenu(seed string) []Menu {
	menus := []Menu{}
	resp, err := http.Get(seed)
	if err != nil {
		log.Fatalf("get menu page err:%v\n", err)
	}
	defer resp.Body.Close()

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	doc.Find("#stab1 > ul > li > a").Each(func(i int, s *goquery.Selection) {
		href, exist := s.Attr("href")
		if !exist {
			log.Fatal("href not exist")
		}
		title, exist := s.Attr("title")
		if !exist {
			log.Fatal("title not exist")
		}
		menus = append(menus, Menu{Addr: href, Name: title})
	})
	return menus
}
